const requireDirectory = require('require-directory');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const koaStatic = require('koa-static');
const path = require('path');
const { catchError } = require('../middlewares/exception');
const { responseTime } = require('../middlewares/responseTime');

import routerParser from '../utils/routerParser';
import config from '../config/core';

// 接口地址访问上下文
const ROOT_BASE_URL = config.ROOT_BASE_URL;

/**
 * 初始化接口路由配置
 * @param {*} app
 */
const initLoadRouters = (app) => {
  const apiDirectorys = [
    path.join(process.cwd(), 'src', 'api'),
  ]

  const rootRouter = new Router();
  function whenLoadModule (obj) {
    const router = obj.default;
    if (router instanceof Router) {
      rootRouter.use(ROOT_BASE_URL, router.routes());
      app.use(rootRouter.routes());
    } else {
      // 采用模板的写法
      const { methods, prefix } = router;
      const childRouter = routerParser(methods, prefix);
      rootRouter.use(ROOT_BASE_URL, childRouter.routes());
      app.use(rootRouter.routes());
    }
  }

  apiDirectorys.forEach(apiDirectory => {
    requireDirectory(module, apiDirectory, { extensions: ['js', 'json', 'coffee'], visit: whenLoadModule });
  })
};

module.exports = (app) => {
  // 统计请求时间
  app.use(responseTime);

  // 可以指定多个静态目录
  app.use(koaStatic(path.join(__dirname, '..', 'static')));

  app.use(bodyParser());

  // 处理接口返回数据
  app.use(catchError);

  initLoadRouters(app);
};
